<template>
  <div class="doctor-workbench">
    <Row :gutter="20">
      <Col span="18">
        <!-- 主工作区 -->
        <Card class="workbench-card">
          <div slot="title" class="workbench-header">
            <h2>医生工作台</h2>
            <div class="date-info">
              <Icon type="md-calendar" />
              <span>{{ currentDate }}</span>
              <Button type="primary" size="small" style="margin-left: 20px" @click="refreshData">
                <Icon type="md-refresh" :class="{ 'loading-icon': isLoading }" />刷新
              </Button>
            </div>
          </div>
          
          <!-- 状态统计卡片 -->
          <Row :gutter="16" class="stat-cards">
            <Col span="8" v-for="(stat, type) in patientStats" :key="type">
              <Card :class="['stat-card', type]">
                <div class="stat-content">
                  <div class="stat-number">{{ stat.count }}</div>
                  <div class="stat-label">{{ stat.label }}</div>
                </div>
                <div class="stat-icon">
                  <Icon :type="stat.icon" size="36" />
                </div>
              </Card>
            </Col>
          </Row>
          
          <!-- 患者列表标签页 -->
          <Tabs v-model="currentTab" class="patient-tabs">
            <TabPane v-for="(list, type) in patientLists" :key="type" :label="list.label" :name="type">
              <Spin v-if="list.loading" size="large" fix />
              <div v-else-if="list.data.length === 0" class="empty-list">
                <Icon type="md-happy" size="32" />
                <p>{{ list.emptyText }}</p>
              </div>
              <div v-else class="patient-list">
                <patient-card
                  v-for="patient in list.data"
                  :key="patient.id"
                  :patient="patient"
                  :status="type"
                  @status-change="handlePatientStatusChange"
                  @view-history="viewPatientHistory"
                />
              </div>
            </TabPane>
          </Tabs>
        </Card>
      </Col>
      
      <!-- 侧边栏 -->
      <Col span="6">
        <Card class="sidebar-card">
          <div slot="title">
            <Icon type="md-person" />
            <span>医生信息</span>
          </div>
          <Spin v-if="isLoading" size="large" fix />
          <div v-else>
            <div class="doctor-profile">
              <Avatar size="large" :src="doctorInfo.avatar || defaultAvatar" />
              <div class="doctor-info">
                <h3>{{ doctorInfo.name || '未知' }}</h3>
                <p>{{ doctorInfo.department || '未知' }} | {{ doctorInfo.title || '未知' }}</p>
              </div>
            </div>
            <Divider />
            <div class="schedule-preview">
              <div class="preview-header">
                <h3>今日排班</h3>
                <Button type="text" @click="viewSchedule">查看完整排班</Button>
              </div>
              <div class="schedule-time">
                <div class="time-block" v-for="(schedule, period) in doctorInfo.schedules" :key="period">
                  <span>{{ schedule.label }}</span>
                  <span>{{ schedule.time || '暂无排班' }}</span>
                </div>
              </div>
            </div>
            <Divider />
            <div class="quick-actions">
              <h3>快捷操作</h3>
              <Button type="primary" long @click="createNewMedicalRecord" :loading="actionLoading.newRecord">
                <Icon type="md-add" />新建病历
              </Button>
              <Button type="success" long style="margin-top: 10px" @click="viewMedicineList" :loading="actionLoading.medicineList">
                <Icon type="md-medkit" />药品目录
              </Button>
              <Button type="info" long style="margin-top: 10px" @click="viewPatientList" :loading="actionLoading.patientList">
                <Icon type="md-people" />患者列表
              </Button>
            </div>
          </div>
        </Card>
      </Col>
    </Row>
    
    <!-- 模态框组件 -->
    <PatientListModal
      v-model="showPatientListModal"
      :loading="modalLoading"
      @close="handleModalClose"
    />
    <ScheduleModal
      v-model="showScheduleModal"
      :userId="userId"
    />
    <MedicineModal
      v-model="showMedicineModal"
      @on-select="handleMedicineSelect"
    />
  </div>
</template>

<script>
import PatientCard from './components/PatientCard.vue'
import PatientListModal from './components/PatientListModal.vue'
import ScheduleModal from './components/ScheduleModal.vue'
import MedicineModal from './components/MedicineModal.vue'
import { getWaitingPatients, getInProgressPatients, getCompletedPatients, getDoctorInfo, getDoctorSchedules, getPatientList } from '@/api/medical-dashboard'
import { mapGetters } from 'vuex'
import Cookies from 'js-cookie'

export default {
  name: 'Dashboard',
  components: {
    PatientCard,
    PatientListModal,
    ScheduleModal,
    MedicineModal
  },
  data() {
    return {
      showPatientListModal: false,
      showScheduleModal: false,
      showMedicineModal: false,
      modalLoading: false,
      currentTab: 'waiting',
      currentDate: this.formatDate(new Date()),
      isLoading: false,
      actionLoading: {
        newRecord: false,
        medicineList: false,
        patientList: false
      },
      defaultAvatar: 'https://via.placeholder.com/100',
      patientStats: {
        waiting: { count: 0, label: '待诊患者', icon: 'md-people', status: 0 },
        inProgress: { count: 0, label: '诊疗中', icon: 'md-pulse', status: 1 },
        completed: { count: 0, label: '已诊患者', icon: 'md-checkmark-circle', status: 2 }
      },
      patientLists: {
        waiting: {
          label: '待诊患者',
          data: [],
          loading: false,
          emptyText: '暂无待诊患者',
          status: 0
        },
        inProgress: {
          label: '诊疗中',
          data: [],
          loading: false,
          emptyText: '暂无诊疗中患者',
          status: 1
        },
        completed: {
          label: '已诊患者',
          data: [],
          loading: false,
          emptyText: '暂无已诊患者',
          status: 2
        }
      },
      doctorInfo: {
        name: '',
        department: '',
        title: '',
        avatar: '',
        schedules: {
          morning: { label: '上午', time: '' },
          afternoon: { label: '下午', time: '' }
        }
      },
      scheduleParams: {
        startDate: this.formatDateForAPI(new Date()),
        endDate: this.formatDateForAPI(new Date(new Date().setDate(new Date().getDate() + 14)))
      }
    }
  },
  computed: {
    ...mapGetters(['userId']),
    currentPatientList() {
      return this.patientLists[this.currentTab].data;
    }
  },
  methods: {
    formatDate(date) {
      const options = { year: 'numeric', month: 'long', day: 'numeric', weekday: 'long' };
      return new Date(date).toLocaleDateString('zh-CN', options);
    },
    formatDateForAPI(date) {
      return date.toISOString().split('T')[0];
    },
    async refreshData() {
      if (this.isLoading) return;
      this.isLoading = true;
      try {
        await Promise.all([
          this.loadDoctorInfo(),
          this.loadPatientLists()
        ]);
      } catch (error) {
        this.$Message.error('刷新数据失败：' + error.message);
      } finally {
        this.isLoading = false;
      }
    },
    async loadDoctorInfo() {
      try {
        console.log('Loading doctor info for userId:', this.userId);
        const response = await getDoctorInfo(this.userId);
        console.log('Doctor info response:', response);
        if (response.success) {
          const schedules = response.result.schedules || {};
          console.log('Schedules from response:', schedules);
          
          this.doctorInfo = {
            name: response.result.name || '未知',
            department: response.result.department || '未知',
            title: response.result.title || '未知',
            avatar: response.result.avatar || this.defaultAvatar,
            schedules: {
              morning: { 
                label: '上午', 
                time: schedules.morning ? schedules.morning.time : '暂无排班'
              },
              afternoon: { 
                label: '下午', 
                time: schedules.afternoon ? schedules.afternoon.time : '暂无排班'
              }
            }
          };
          console.log('Updated doctor info:', this.doctorInfo);
        } else {
          console.error('Failed to get doctor info:', response);
          this.$Message.error(response.message || '获取医生信息失败');
        }
      } catch (error) {
        console.error('Error in loadDoctorInfo:', error);
        this.$Message.error('获取医生信息失败：' + error.message);
      }
    },
    async loadPatientLists() {
      const loadFunctions = {
        waiting: getWaitingPatients,
        inProgress: getInProgressPatients,
        completed: getCompletedPatients
      };

      for (const [type, list] of Object.entries(this.patientLists)) {
        list.loading = true;
        try {
          console.log(`Loading ${type} patients for userId:`, this.userId);
          const response = await loadFunctions[type](this.userId);
          console.log(`${type} patients response:`, response);
          if (response.success) {
            list.data = response.result.map(patient => ({
              id: patient.id,
              name: patient.name,
              gender: patient.gender || '未知',
              age: patient.age || '未知',
              phone: patient.phone || '未知',
              visitTime: patient.visitTime || '未知',
              status: patient.status,
              chiefComplaint: patient.chiefComplaint || '暂无主诉信息'
            }));
            this.patientStats[type].count = response.result.length;
            console.log(`Updated ${type} patients:`, list.data);
          } else {
            console.error(`Failed to get ${type} patients:`, response);
            this.$Message.error(response.message || `获取${list.label}失败`);
          }
        } catch (error) {
          console.error(`Error in loading ${type} patients:`, error);
          this.$Message.error(`获取${list.label}失败：${error.message}`);
        } finally {
          list.loading = false;
        }
      }
    },
    handlePatientStatusChange(patient, newStatus) {
      // 处理患者状态变更
      this.refreshData();
    },
    viewPatientHistory(patient) {
      // 查看患者历史记录
      this.$router.push({
        name: 'patientHistory',
        params: { patientId: patient.id }
      });
    },
    async createNewMedicalRecord() {
      this.actionLoading.newRecord = true;
      try {
        // 跳转到新建病历页面
        this.$router.push({ name: 'newMedicalRecord' });
      } finally {
        this.actionLoading.newRecord = false;
      }
    },
    async viewMedicineList() {
      this.actionLoading.medicineList = true;
      try {
        this.showMedicineModal = true;
      } finally {
        this.actionLoading.medicineList = false;
      }
    },
    viewPatientList() {
      this.showPatientListModal = true;
    },
    handleModalClose() {
      this.showPatientListModal = false;
      this.refreshData();
    },
    viewSchedule() {
      this.showScheduleModal = true;
      // 加载未来两周的排班数据
      this.loadScheduleData();
    },
    async loadScheduleData() {
      try {
        const response = await getDoctorSchedules(this.userId, this.scheduleParams);
        if (response.success) {
          // 处理排班数据
          console.log('Schedule data loaded:', response.result);
        } else {
          this.$Message.error(response.message || '获取排班信息失败');
        }
      } catch (error) {
        console.error('Error loading schedule data:', error);
        this.$Message.error('获取排班信息失败：' + error.message);
      }
    },
    async loadPatientList() {
      this.loadingPatients = true;
      console.log('开始加载患者列表');
      
      try {
        // 调用API获取患者列表
        console.log('准备发送请求到医生工作台API');
        const response = await getPatientList({
          userId: this.userId,
          pageNumber: 1,
          pageSize: 10,
          searchKey: ''
        }).catch(error => {
          console.error('请求发送失败:', error);
          throw error;
        });
        console.log('收到服务器响应:', response);
        
        if (response && response.success && response.result && response.result.length > 0) {
          this.patientList = response.result;
          console.log('成功获取患者列表，数量:', this.patientList.length);
        } else {
          console.warn('API返回空数据或错误:', response);
          this.$Message.warning('未获取到患者数据，请联系管理员');
          this.patientList = [];
        }
      } catch (error) {
        console.error('加载患者列表异常:', error);
        this.$Message.error('获取患者列表失败: ' + (error.message || '未知错误'));
        this.patientList = [];
      } finally {
        this.loadingPatients = false;
        console.log('患者列表加载完成');
      }
    },
    
    async searchPatients() {
      if (!this.patientSearchKey.trim()) {
        this.loadPatientList();
        return;
      }
      
      this.loadingPatients = true;
      console.log('开始搜索患者，关键词:', this.patientSearchKey);
      
      try {
        // 调用API搜索患者
        console.log('准备发送搜索请求');
        const response = await getPatientList({
          userId: this.userId,
          pageNumber: 1,
          pageSize: 10,
          searchKey: this.patientSearchKey
        }).catch(error => {
          console.error('搜索请求发送失败:', error);
          throw error;
        });
        console.log('收到搜索响应:', response);
        
        if (response && response.success && response.result) {
          this.patientList = response.result;
          console.log('搜索成功，找到患者数量:', this.patientList.length);
          
          if (this.patientList.length === 0) {
            this.$Message.info('未找到匹配的患者');
          }
        } else {
          console.warn('搜索API返回错误:', response);
          this.$Message.warning('搜索患者失败，请稍后重试');
          this.patientList = [];
        }
      } catch (error) {
        console.error('搜索患者异常:', error);
        this.$Message.error('搜索患者失败: ' + (error.message || '未知错误'));
        this.patientList = [];
      } finally {
        this.loadingPatients = false;
        console.log('患者搜索完成');
      }
    },
    handleMedicineSelect(medicine) {
      console.log('选中的药品:', medicine);
      // 这里可以处理选中的药品，比如添加到处方等
      this.$Message.success(`已选择药品：${medicine.name}`);
    }
  },
  created() {
    this.refreshData();
  }
}
</script>

<style lang="less" scoped>
.doctor-workbench {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 64px);
}

.workbench-card {
  margin-bottom: 20px;
}

.workbench-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.workbench-header h2 {
  margin: 0;
  font-size: 20px;
  font-weight: 500;
}

.date-info {
  display: flex;
  align-items: center;
  font-size: 14px;
  color: #606266;
}

.date-info .ivu-icon {
  margin-right: 5px;
}

.stat-cards {
  margin-bottom: 20px;
}

.stat-card {
  display: flex;
  justify-content: space-between;
  padding: 20px;
  border-radius: 4px;
  color: white;
}

.stat-card.waiting {
  background: linear-gradient(135deg, #36D1DC 0%, #5B86E5 100%);
}

.stat-card.inProgress {
  background: linear-gradient(135deg, #FF9966 0%, #FF5E62 100%);
}

.stat-card.completed {
  background: linear-gradient(135deg, #56ab2f 0%, #a8e063 100%);
}

.stat-content {
  display: flex;
  flex-direction: column;
}

.stat-number {
  font-size: 28px;
  font-weight: bold;
  margin-bottom: 5px;
}

.stat-label {
  font-size: 14px;
}

.empty-list {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 40px 0;
  color: #909399;
}

.empty-list p {
  margin-top: 10px;
}

.doctor-profile {
  display: flex;
  align-items: center;
  margin-bottom: 15px;
}

.doctor-info {
  margin-left: 15px;
}

.doctor-info h3 {
  margin: 0 0 5px 0;
  font-size: 16px;
}

.doctor-info p {
  margin: 0;
  color: #606266;
  font-size: 14px;
}

.schedule-preview {
  margin-bottom: 15px;
}

.preview-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.preview-header h3 {
  margin: 0;
  font-size: 16px;
}

.schedule-time {
  display: flex;
  flex-direction: column;
}

.time-block {
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;
  font-size: 14px;
}

.quick-actions h3 {
  margin: 0 0 15px 0;
  font-size: 16px;
}

.sidebar-card {
  height: 100%;
}

.patient-tabs {
  margin-top: 10px;
}
</style> 